﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using Telerik.Windows.Controls;
using TruckScale.Helpers;
using TruckScale.Models;

namespace TruckScale.ViewModels
{
  public partial class MainViewModel
  {
    public DelegateCommand SwitchThemeCommand { get; private set; }
    public DelegateCommand ManagingDockingCommand { get; private set; }
    public DelegateCommand OpenWindowCommand { get; private set; }
    public DelegateCommand CloseWindowCommand { get; set; }
    public DelegateCommand OpenExeCommand { get; set; }
    public DelegateCommand RefreshWeighFormCommand { get; set; }
    public bool IsInitialized { get; private set; }
    public bool IsReg { get; private set; }

    public MainViewModel()
    {
      //初始化界面风格
      SetTheme(Global._weighConfig["Theme"]);

      //初始化所有属性
      InitializeProps();

      //初始化所有命令
      InitializeCommands();

      Global._isReg = RegisterHelper.Verify(RegisterHelper.GetHdInfo()).Equals(Global._weighConfig["RegCode"]);
      IsInitialized = true;
    }

    //初始化所有属性
    private void InitializeProps()
    {
      //初始化UI相关属性
      MainFontSize = Global._weighConfig["MainFontSize"];
      WeighTemplateName = Global._weighConfig["WeighTemplateName"];

      //初始化登录相关属性
      InitLoginProps();

      //初始化重量数字相关属性
      InitWeighNumProps();

      //初始化外设相关属性
      InitPeripheralsProps();

      //初始化过磅单相关属性
      InitWeighFormProps();

      //初始化过磅按钮相关属性
      InitWeighModeProps();

      //初始化称重记录相关属性
      InitWeighRecordProps();

      //初始化摄像头相关属性
      InitMonitorProps();
      InitLPRProps();
    }

    private void InitializeCommands()
    {
      SwitchThemeCommand = new DelegateCommand((obj) => SetTheme(obj.ToString()));
      ManagingDockingCommand = new DelegateCommand((obj) => ShowPanelTitle = obj.ToString());
      OpenWindowCommand = new DelegateCommand(OnOpenWindowCommandExecuted);
      CloseWindowCommand = new DelegateCommand((obj) => Application.Current.MainWindow.Close());
      OpenExeCommand = new DelegateCommand((obj) => Process.Start(obj.ToString()));
      RefreshWeighFormCommand = new DelegateCommand((obj) =>
      {
        WeighRecord = new Models.WeighRecordModel();
        weighingStatus = WeighingStatus.Ready;
        InitWeighFormProps();
        CheckBtnEnable();
      });
      InitLoginCommands();
      InitWeighModeCommands();
      InitWeighRecordCommands();
    }

    private void SetTheme(string theme)
    {
      Application.Current.Resources.MergedDictionaries.Clear();
      Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
      {
        Source = new Uri("/Telerik.Windows.Themes." + theme + ";component/Themes/System.Windows.xaml", UriKind.RelativeOrAbsolute)
      });
      Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
      {
        Source = new Uri("/Telerik.Windows.Themes." + theme + ";component/Themes/Telerik.Windows.Controls.xaml", UriKind.RelativeOrAbsolute)
      });
      Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
      {
        Source = new Uri("/Telerik.Windows.Themes." + theme + ";component/Themes/Telerik.Windows.Controls.Input.xaml", UriKind.RelativeOrAbsolute)
      });
      Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
      {
        Source = new Uri("/Telerik.Windows.Themes." + theme + ";component/Themes/Telerik.Windows.Controls.RibbonView.xaml", UriKind.RelativeOrAbsolute)
      });
      Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
      {
        Source = new Uri("/Telerik.Windows.Themes." + theme + ";component/Themes/Telerik.Windows.Controls.Docking.xaml", UriKind.RelativeOrAbsolute)
      });
      Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
      {
        Source = new Uri("/Telerik.Windows.Themes." + theme + ";component/Themes/Telerik.Windows.Controls.GridView.xaml", UriKind.RelativeOrAbsolute)
      });
      Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
      {
        Source = new Uri("Styles/RibbonWindowStyle.xaml", UriKind.RelativeOrAbsolute)
      });

      Global._weighConfig["Theme"] = theme;
      WeighConfigModel.UpdateConfig("Theme", theme);

      SettingFontSize(Global._weighConfig["Theme"]);
    }

    private void SettingFontSize(string theme)
    {
      string fontSize = Global._weighConfig["MainFontSize"];

      switch (theme)
      {
        case "Windows8":
          Windows8Palette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Windows8Touch":
          Windows8TouchPalette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Office2013":
          Office2013Palette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Office2019":
          Office2019Palette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "VisualStudio2013":
          VisualStudio2013Palette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Office2016":
          Office2016Palette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Office2016Touch":
          Office2016TouchPalette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Green":
          GreenPalette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Fluent":
          FluentPalette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Material":
          MaterialPalette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "Crystal":
          CrystalPalette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        case "VisualStudio2019":
          VisualStudio2019Palette.Palette.FontSize = Convert.ToDouble(fontSize);
          break;
        default:
          break;
      }
    }

    // 维护一个静态字典来跟踪已打开的 RadWindow 实例
    private static Dictionary<string, RadWindow> openedWindows = new Dictionary<string, RadWindow>();

    private void OnOpenWindowCommandExecuted(object obj)
    {
      //类的完全限定名（包括命名空间）
      string viewName = "TruckScale.Views." + obj.ToString();

      // 获取窗口类型
      Type windowType = Type.GetType(viewName);
      if (windowType == null)
      {
        throw new ArgumentException($"无法找到类型 {viewName}");
      }

      // 检查字典中是否已有此类型的窗口实例
      if (openedWindows.TryGetValue(viewName, out RadWindow existingWindow))
      {
        // 如果窗口已打开，将其置顶
        if (existingWindow.WindowState == WindowState.Minimized)
        {
          existingWindow.WindowState = WindowState.Normal;
        }
        existingWindow.BringToFront();
        return;
      }

      // 如果窗口未打开，则通过反射创建新实例
      RadWindow window = Activator.CreateInstance(windowType) as RadWindow;
      window.Owner = Application.Current.MainWindow;

      // 在窗口关闭时将其从字典中移除
      window.Closed += (s, e) => openedWindows.Remove(viewName);

      // 将新窗口添加到字典
      openedWindows[viewName] = window;

      //var rst = window.ShowDialog();
      if (viewName.Contains("QS"))
      {
        //window.Owner = null;
        window.Show();
      }
      else
      {
        window.ShowDialog();
      }

      //弹窗关闭后刷新界面
      if (obj.ToString().Equals("SSFormView"))
      {
        InitWeighFormProps(); //表单配置完刷新主界面表单字段
        InitWeighRecordProps();//表单配置完刷新主界面称重记录字段
      }
      if (obj.ToString().StartsWith("DM"))
      {
        InitWeighFormProps(); //增加字段后刷新表单下拉框
      }
      if (obj.ToString().Equals("SSWeighView"))
      {
        InitWeighNumProps(); //称重串口会修改
        InitWeighModeProps(); //按钮显示
      }
      if (obj.ToString().Equals("SSHardwareView"))
      {
        InitPeripheralsProps(); //IO控制器串口会修改
        InitMonitorProps(); //摄像头IP会改
        InitLPRProps();//摄像头IP会改
      }
      if (obj.ToString().Equals("RegView") || obj.ToString().Equals("UploadView"))
      {
        Global._weighConfig = WeighConfigModel.SelectConfig();  //注册和上传页面更新了称重配置表
      }

      GC.Collect();
    }


  }
}
